package com.sz.mes.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.diboot.core.util.BeanUtils;
import com.diboot.core.util.D;
import com.diboot.core.util.V;
import com.diboot.file.util.ExcelHelper;
import com.sz.mes.dto.GoodsDTO;
import com.sz.mes.entity.Goods;
import com.sz.mes.entity.PurchaseOrder;
import com.sz.mes.excel.model.GoodsExportModel;
import com.sz.mes.excel.model.RequestPurchaseExportModel;
import com.sz.mes.mapper.RequestPurchaseMapper;
import com.sz.mes.vo.PurchaseOrderListVO;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.constraints.Length;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.diboot.core.vo.*;
import com.diboot.iam.annotation.OperationCons;
import com.diboot.iam.annotation.BindPermission;
import com.diboot.iam.annotation.Log;
import com.sz.mes.entity.RequestPurchase;
import com.sz.mes.dto.RequestPurchaseDTO;
import com.sz.mes.vo.RequestPurchaseListVO;
import com.sz.mes.vo.RequestPurchaseDetailVO;
import com.sz.mes.service.RequestPurchaseService;
import com.sz.mes.controller.BaseCustomCrudRestController;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

/**
 * 请购订单 相关Controller
 *
 * @author hem
 * @version 1.0
 * @date 2023-11-09
 * Copyright © szhs
 */
@RestController
@RequestMapping("/requestPurchase")
@BindPermission(name = "请购订单")
@Slf4j
public class RequestPurchaseController extends BaseCustomCrudRestController<RequestPurchase> {

    @Autowired
    private RequestPurchaseService requestPurchaseService;

    @Autowired
    private RequestPurchaseMapper requestPurchaseMapper;

    /**
     * 查询ViewObject的分页数据
     * <p>
     * url请求参数示例: /list?field=abc&pageIndex=1&orderBy=abc:DESC
     * </p>
     *
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_LIST)
    @BindPermission(name = OperationCons.LABEL_LIST, code = OperationCons.CODE_READ)
    @GetMapping("/list")
    public JsonResult getViewObjectListMapping(RequestPurchaseDTO queryDto, Pagination pagination) throws Exception {
        QueryWrapper<RequestPurchase> requestPurchaseQueryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(queryDto.getSpecification())) {
            requestPurchaseQueryWrapper.like("specification", queryDto.getSpecification());
        } else if (!StringUtils.isEmpty(queryDto.getProductName())) {
            requestPurchaseQueryWrapper.like("product_name", queryDto.getProductName());
        } else if (!StringUtils.isEmpty(queryDto.getProductNum())) {
            requestPurchaseQueryWrapper.like("product_num", queryDto.getProductNum());
        } else if (!StringUtils.isEmpty(queryDto.getPlanNum())) {
            requestPurchaseQueryWrapper.like("plan_num", queryDto.getPlanNum());
        } else if (!StringUtils.isEmpty(queryDto.getReceiptNum())) {
            requestPurchaseQueryWrapper.like("receipt_num", queryDto.getReceiptNum());
        } else if (!StringUtils.isEmpty(queryDto.getProductNameTwo())) {
            requestPurchaseQueryWrapper.like("product_name_two", queryDto.getProductNameTwo());
        } else {
//            return super.getViewObjectList(queryDto, pagination.setOrderBy("receipt_num:DESC"), RequestPurchaseListVO.class);
            return super.getViewObjectList(queryDto, pagination.setOrderBy("id:ASC"), RequestPurchaseListVO.class);
        }
        return super.getEntityListWithPaging(requestPurchaseQueryWrapper, pagination.setOrderBy("id:ASC"));
    }

    /**
     * 根据资源id查询ViewObject
     *
     * @param id ID
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_DETAIL)
    @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
    @GetMapping("/{id}")
    public JsonResult getViewObjectMapping(@PathVariable("id") Long id) throws Exception {
        return super.getViewObject(id, RequestPurchaseDetailVO.class);
    }

    /**
     * 创建资源对象
     *
     * @param entity
     * @return JsonResult
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_CREATE)
    @BindPermission(name = OperationCons.LABEL_CREATE, code = OperationCons.CODE_WRITE)
    @PostMapping("/")
    public JsonResult createEntityMapping(@Valid @RequestBody RequestPurchase entity) throws Exception {
        QueryWrapper<RequestPurchase> requestPurchaseQueryWrapper = new QueryWrapper<>();
        requestPurchaseQueryWrapper.eq("receipt_num", entity.getReceiptNum());
        requestPurchaseQueryWrapper.eq("receipt_num_row", entity.getReceiptNumRow());
        RequestPurchase requestPurchase = requestPurchaseMapper.selectOne(requestPurchaseQueryWrapper);
        if (requestPurchase == null) {
            return super.createEntity(entity);
        } else {
            return JsonResult.FAIL_OPERATION("该订单已存在");
        }
    }

    /**
     * 根据ID更新资源对象
     *
     * @param entity
     * @return JsonResult
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_UPDATE)
    @BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
    @PutMapping("/{id}")
    public JsonResult updateEntityMapping(@PathVariable("id") Long id, @Valid @RequestBody RequestPurchase entity) throws Exception {
        try {
            QueryWrapper<RequestPurchase> requestPurchaseQueryWrapper = new QueryWrapper<>();
            requestPurchaseQueryWrapper.eq("receipt_num", entity.getReceiptNum());
            requestPurchaseQueryWrapper.eq("receipt_num_row", entity.getReceiptNumRow());
            RequestPurchase requestPurchase = requestPurchaseMapper.selectOne(requestPurchaseQueryWrapper);
            RequestPurchase currentRequestPurchase = requestPurchaseMapper.selectById(id);
            @Length(max = 100, message = "行号长度应小于100") String receiptNumRow = entity.getReceiptNumRow();
            @Length(max = 100, message = "单据编号长度应小于100") String receiptNum = entity.getReceiptNum();
            if (entity.getReceiptNum().equals(currentRequestPurchase.getReceiptNum())
                    && entity.getReceiptNumRow().equals(currentRequestPurchase.getReceiptNumRow())) {
                return super.updateEntity(id, entity);
            } else {
                if (requestPurchase != null) {
                    return JsonResult.FAIL_EXCEPTION("该订单已存在");
                } else {
                    return super.updateEntity(id, entity);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.FAIL_EXCEPTION("请检查单据编号及行号");
        }

    }

    /**
     * 根据id删除资源对象
     *
     * @param id
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_DELETE)
    @BindPermission(name = OperationCons.LABEL_DELETE, code = OperationCons.CODE_WRITE)
    @DeleteMapping("/{id}")
    public JsonResult deleteEntityMapping(@PathVariable("id") Long id) throws Exception {
        return super.deleteEntity(id);
    }

    /**
     * excel导入
     *
     * @param entity
     * @return JsonResult
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_CREATE)
    // @BindPermission(name = OperationCons.LABEL_CREATE, code = OperationCons.CODE_WRITE)
    @PostMapping("/excel")
    public JsonResult insert(@Valid @RequestBody RequestPurchase entity) throws Exception {
        List<String> receiptNumAndRowList = new ArrayList<>();
        String excelData = entity.getExcelData();
        JSONArray objects = JSONObject.parseArray(excelData);
        for (Object object : objects) {
            HashMap<String, String> hashMap = JSONObject.parseObject(JSONObject.toJSONString(object), HashMap.class);
            String receiptNum = hashMap.get("单据编号");
            String rowNum = hashMap.get("行号");
            String receiptNumAndRow = receiptNum + "-" + rowNum;
            receiptNumAndRowList.add(receiptNumAndRow);
        }
        QueryWrapper<RequestPurchase> requestPurchaseQueryWrapper = new QueryWrapper<>();
        for (String receiptNumAndRow : receiptNumAndRowList) {
            String[] receiptNumAndRowArray = receiptNumAndRow.split("-");
            requestPurchaseQueryWrapper.eq("receipt_num", receiptNumAndRowArray[0]);
            requestPurchaseQueryWrapper.eq("receipt_num_row", receiptNumAndRowArray[1]);
            try {
                RequestPurchase requestPurchase = requestPurchaseMapper.selectOne(requestPurchaseQueryWrapper);
                // 单据编号，行号不存在的时候，才能新增
                if (requestPurchase == null) {
                    return requestPurchaseService.insert(entity);
                } else {
                    return JsonResult.FAIL_EXCEPTION("该单号已存在,导入失败");
                }
            } catch (Exception e) {
                e.printStackTrace();
                return JsonResult.FAIL_EXCEPTION("该单号已存在,导入失败");
            }
        }
        return JsonResult.OK("导入成功");
    }


    /***
     * 请购订单导出
     * @param requestPurchaseDTO
     * @return
     * @throws Exception
     */
    @Log(operation = "导出请购订单", businessObj = "RequestPurchase")
//    @BindPermission(name = OperationCons.LABEL_EXPORT, code = OperationCons.CODE_EXPORT)
    @GetMapping("/export")
    public JsonResult export(RequestPurchaseDTO requestPurchaseDTO, @RequestParam(value = "columns", required = false) List<String> columns,
                             HttpServletResponse response) throws Exception {
        QueryWrapper<RequestPurchase> queryWrapper = super.buildQueryWrapperByQueryParams(requestPurchaseDTO);
        List<RequestPurchase> requestPurchaseList = requestPurchaseService.getViewObjectList(queryWrapper, null, RequestPurchase.class);
        if (V.isEmpty(requestPurchaseList)) {
            return new JsonResult(Status.FAIL_OPERATION, "请购订单列表为空，导出失败");
        }
        String fileName = "请购订单导出_" + D.today() + ".xlsx";
        List<RequestPurchaseExportModel> dataList = this.entityList2ExcelList(requestPurchaseList);
        ExcelHelper.exportExcel(response, fileName, RequestPurchaseExportModel.class, columns, dataList);
        return null;
    }

    /***
     * 实体列表转excel列表
     * @param requestPurchaseList
     * @return
     */
    private List<RequestPurchaseExportModel> entityList2ExcelList(List<RequestPurchase> requestPurchaseList) {
        if (V.isEmpty(requestPurchaseList)) {
            return Collections.emptyList();
        }
        List<RequestPurchaseExportModel> excelModelList = new ArrayList<>();
        for (RequestPurchase requestPurchase : requestPurchaseList) {
            RequestPurchaseExportModel exportModel = new RequestPurchaseExportModel();
            BeanUtils.copyProperties(requestPurchase, exportModel);
            excelModelList.add(exportModel);
        }
        return excelModelList;
    }
}
